package com.campus.lostandfound.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.lostandfound.entity.*;
import com.campus.lostandfound.mapper.*;
import com.campus.lostandfound.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 管理员服务实现
 */
@Service
public class AdminServiceImpl implements AdminService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    // ==================== 用户管理 ====================
    
    @Override
    public List<User> getAllUsers() {
        List<User> users = userMapper.selectList(null);
        // 清除敏感信息
        users.forEach(user -> {
            user.setPassword(null);
            user.setSalt(null);
        });
        return users;
    }
    
    @Override
    @Transactional
    public boolean enableUser(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        user.setStatus(1);
        return userMapper.updateById(user) > 0;
    }
    
    @Override
    @Transactional
    public boolean disableUser(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 不能禁用超级管理员
        if (isSuperAdmin(userId)) {
            throw new RuntimeException("不能禁用超级管理员");
        }
        user.setStatus(0);
        return userMapper.updateById(user) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteUser(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 不能删除超级管理员
        if (isSuperAdmin(userId)) {
            throw new RuntimeException("不能删除超级管理员");
        }
        // 删除用户的角色关联
        userRoleMapper.deleteByUserId(userId);
        // 删除用户
        return userMapper.deleteById(userId) > 0;
    }
    
    @Override
    @Transactional
    public boolean assignRoleToUser(Long userId, Long roleId) {
        // 检查用户和角色是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        Role role = roleMapper.selectById(roleId);
        if (role == null) {
            throw new RuntimeException("角色不存在");
        }
        
        // 检查是否已经分配
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("role_id", roleId);
        if (userRoleMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("用户已拥有该角色");
        }
        
        // 创建关联
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        boolean result = userRoleMapper.insert(userRole) > 0;
        
        // 同步更新 user.role 字段（用于前端菜单显示）
        if (result) {
            syncUserRoleField(userId);
        }
        
        return result;
    }
    
    @Override
    @Transactional
    public boolean removeUserRole(Long userId, Long roleId) {
        // 不能移除超级管理员角色
        Role role = roleMapper.selectById(roleId);
        if (role != null && "SUPER_ADMIN".equals(role.getRoleCode())) {
            throw new RuntimeException("不能移除超级管理员角色");
        }
        
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("role_id", roleId);
        boolean result = userRoleMapper.delete(wrapper) > 0;
        
        // 同步更新 user.role 字段（用于前端菜单显示）
        if (result) {
            syncUserRoleField(userId);
        }
        
        return result;
    }
    
    @Override
    public List<Role> getUserRoles(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }
    
    @Override
    public List<Permission> getUserPermissions(Long userId) {
        return permissionMapper.selectPermissionsByUserId(userId);
    }
    
    // ==================== 角色管理 ====================
    
    @Override
    public List<Role> getAllRoles() {
        return roleMapper.selectList(null);
    }
    
    @Override
    @Transactional
    public boolean addRole(Role role) {
        // 检查角色编码是否已存在
        Role existingRole = roleMapper.selectByRoleCode(role.getRoleCode());
        if (existingRole != null) {
            throw new RuntimeException("角色编码已存在");
        }
        return roleMapper.insert(role) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteRole(Long roleId) {
        Role role = roleMapper.selectById(roleId);
        if (role == null) {
            throw new RuntimeException("角色不存在");
        }
        // 不能删除系统内置角色
        if ("SUPER_ADMIN".equals(role.getRoleCode()) || "ADMIN".equals(role.getRoleCode()) || "USER".equals(role.getRoleCode())) {
            throw new RuntimeException("不能删除系统内置角色");
        }
        
        // 删除角色的权限关联
        rolePermissionMapper.deleteByRoleId(roleId);
        // 删除角色的用户关联
        userRoleMapper.deleteByRoleId(roleId);
        // 删除角色
        return roleMapper.deleteById(roleId) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateRole(Role role) {
        Role existingRole = roleMapper.selectById(role.getId());
        if (existingRole == null) {
            throw new RuntimeException("角色不存在");
        }
        // 不能修改系统内置角色的编码
        if ("SUPER_ADMIN".equals(existingRole.getRoleCode()) || "ADMIN".equals(existingRole.getRoleCode()) || "USER".equals(existingRole.getRoleCode())) {
            if (!existingRole.getRoleCode().equals(role.getRoleCode())) {
                throw new RuntimeException("不能修改系统内置角色的编码");
            }
        }
        return roleMapper.updateById(role) > 0;
    }
    
    @Override
    @Transactional
    public boolean assignPermissionToRole(Long roleId, Long permissionId) {
        // 检查角色和权限是否存在
        Role role = roleMapper.selectById(roleId);
        if (role == null) {
            throw new RuntimeException("角色不存在");
        }
        Permission permission = permissionMapper.selectById(permissionId);
        if (permission == null) {
            throw new RuntimeException("权限不存在");
        }
        
        // 检查是否已经分配
        QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId).eq("permission_id", permissionId);
        if (rolePermissionMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("角色已拥有该权限");
        }
        
        // 创建关联
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(roleId);
        rolePermission.setPermissionId(permissionId);
        return rolePermissionMapper.insert(rolePermission) > 0;
    }
    
    @Override
    @Transactional
    public boolean removeRolePermission(Long roleId, Long permissionId) {
        QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId).eq("permission_id", permissionId);
        return rolePermissionMapper.delete(wrapper) > 0;
    }
    
    @Override
    public List<Permission> getRolePermissions(Long roleId) {
        return permissionMapper.selectPermissionsByRoleId(roleId);
    }
    
    // ==================== 权限管理 ====================
    
    @Override
    public List<Permission> getAllPermissions() {
        return permissionMapper.selectList(null);
    }
    
    @Override
    @Transactional
    public boolean addPermission(Permission permission) {
        return permissionMapper.insert(permission) > 0;
    }
    
    @Override
    @Transactional
    public boolean deletePermission(Long permissionId) {
        Permission permission = permissionMapper.selectById(permissionId);
        if (permission == null) {
            throw new RuntimeException("权限不存在");
        }
        
        // 删除权限的角色关联
        rolePermissionMapper.deleteByPermissionId(permissionId);
        // 删除权限
        return permissionMapper.deleteById(permissionId) > 0;
    }
    
    @Override
    @Transactional
    public boolean updatePermission(Permission permission) {
        Permission existingPermission = permissionMapper.selectById(permission.getId());
        if (existingPermission == null) {
            throw new RuntimeException("权限不存在");
        }
        return permissionMapper.updateById(permission) > 0;
    }
    
    // ==================== 权限检查 ====================
    
    @Override
    public boolean isSuperAdmin(Long userId) {
        List<Role> roles = roleMapper.selectRolesByUserId(userId);
        return roles.stream().anyMatch(role -> "SUPER_ADMIN".equals(role.getRoleCode()));
    }
    
    @Override
    public boolean hasPermission(Long userId, String permissionCode) {
        // 超级管理员拥有所有权限
        if (isSuperAdmin(userId)) {
            return true;
        }
        
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(userId);
        return permissions.stream().anyMatch(p -> permissionCode.equals(p.getPermissionCode()));
    }
    
    // ==================== 辅助方法 ====================
    
    /**
     * 同步更新 user.role 字段（用于前端菜单显示）
     * 规则：
     * - 有 SUPER_ADMIN 或 ADMIN 角色 → user.role = 1
     * - 只有 USER 角色 → user.role = 0
     * - 没有角色 → user.role = 0
     */
    private void syncUserRoleField(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return;
        }
        
        // 获取用户的所有角色
        List<Role> roles = roleMapper.selectRolesByUserId(userId);
        
        // 判断用户的最高权限角色
        int newRoleValue = 0; // 默认普通用户
        
        for (Role role : roles) {
            if ("SUPER_ADMIN".equals(role.getRoleCode()) || "ADMIN".equals(role.getRoleCode())) {
                newRoleValue = 1; // 管理员
                break;
            }
        }
        
        // 只有当 user.role 值发生变化时才更新
        if (user.getRole() != newRoleValue) {
            user.setRole(newRoleValue);
            userMapper.updateById(user);
        }
    }
}

